<?php
namespace App\Models;

use App\Library\App;
use Phalcon\Mvc\Model;

class Base extends Model {
    private $db;
    protected $memCache;

    public function initialize() {
    }

    /**
     * 获取数据库对象
     *
     * @return \Phalcon\Db\Adapter\Pdo\Mysql
     */
    public function db() {
        if(!is_object($this->db)) {
            $this->db = $this->getDI()->getShared('db');
        }
        return $this->db;
    }

    /**
     * Return internal PDO handler
     *
     * @return \PDO
     */
    public function pdo() {
        return $this->db()->getInternalHandler();
    }

    /**
     * 获取memcache对象
     *
     * @return \Phalcon\Cache\BackendInterface
     */
    public function memCache() {
        if($this->memCache == null) {
            $this->memCache = $this->getDI()->getShared('memCache');
        }
        return $this->memCache;
    }

    /**
     * 封装查询语句
     *
     * @param string $columns
     * @return Model\Query\BuilderInterface
     */
    public function select($columns = '*') {
        return $this->getModelsManager()->createBuilder()->columns($columns);
    }

    /**
     * 记录错误日志
     *
     * @param string $type 数据库操作类型
     * @param string $query 数据库查询语句
     * @param string $reason 失败原因
     * @param string $file 发生的文件
     * @param int    $line 发生错误的行数
     *
     * @return void
     */
    public function errorLog($type, $query, $reason, $file, $line) {
        App::Logger()->error(sprintf("数据库操作失败：类型[%s]，Query[%s]原因[%s][%s:%s]", $type, $query, $reason, $file, $line));
    }
}